package com.xinglong.spider.spider;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.xinglong.spider.util.BaiDuOcrUtils;
import com.xinglong.spider.util.RsaUtils;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.Base64;
import java.util.Map;

/**
 * @Author：胡云峰
 * @Date：2022/12/6 16:31
 */
public class SpiderMain {

    /**
     * 设置请求头
     * @author 胡云峰
     * @param con
     */
    public static void setHeader(Connection con){
        //请求头设置，特别是cookie设置
        con.header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9");
        con.header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36");
        con.header("Host","ypnew.hnggzyjy.cn:9080");
        con.header("Upgrade-Insecure-Requests","1");
        con.header("Connection","keep-alive");
        con.header("Cache-Control","max-age=0");
    }

    /**
     * 获取验证码 并 通过百度ocr识别图片文字
     * @author 胡云峰
     * @throws IOException
     */
    public static void getCaptchaImgAndLogin(String username,String password) throws IOException {
        //获取请求连接
        Connection con = Jsoup.connect("http://ypnew.hnggzyjy.cn:9080/std/captchaImg");

        //设置请求头
        setHeader(con);

        //解析请求结果
        Connection.Response response = con.ignoreContentType(true).method(Connection.Method.GET).execute();
        //查看相应代码
        int statusCode = response.statusCode();
        if (statusCode == 200){
            //获取cookie
            Map<String, String> cookies = response.cookies();
            //获取验证码
            byte[] bytes = response.bodyAsBytes();
            String encodeToString = Base64.getEncoder().encodeToString(bytes);
            //百度ocr识别
            String ocrImage = BaiDuOcrUtils.getOcrMessage(encodeToString);
            // 登录
            doLogin(username,password,ocrImage,cookies);
        }
    }

    /**
     * 登录
     * @author 胡云峰
     * @param username
     * @param password
     * @param ocrImage
     * @param cookies
     * @return
     */
    public static boolean doLogin(String username,String password,String ocrImage,Map<String, String> cookies){
        //获取请求连接
        Connection con = Jsoup.connect("https://ypnew.hnggzyjy.cn:9080/std/loginAuth.html");

        //设置请求头
        setHeader(con);
        con.header("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        con.header("Origin","http://ypnew.hnggzyjy.cn:9080");
        con.header("Referer","http://ypnew.hnggzyjy.cn:9080/std/login.html");
        con.header("X-Requested-With","XMLHttpRequest");
        //设置cookies
        con.cookies(cookies);

        //设置请求参数
        try {
            con.data("username",RsaUtils.encryptByPublicKey(username)); //账号
            con.data("password",RsaUtils.encryptByPublicKey(password)); //密码
            con.data("answer",RsaUtils.encryptByPublicKey(ocrImage));   //验证码
            con.data("activeType",RsaUtils.encryptByPublicKey("1"));//账号类型
        } catch (Exception e) {
            //RSA加密失败
            e.printStackTrace();
        }

        //发起请求
        try {
            Connection.Response response = con.ignoreContentType(true).method(Connection.Method.POST).execute();
            int statusCode = response.statusCode();
            //如果登录成功  获取cookies 和 body
            Map<String, String> cookieMap = response.cookies();
            String body = response.body();
            System.out.println(cookieMap);
            System.out.println(body);

        } catch (IOException e) {
            e.printStackTrace();
        }
        return true;
    }

    public static void main(String[] args) throws IOException {
        //获取验证码并登录
        getCaptchaImgAndLogin("hj10140","wQuYlpYp");
        //
    }
}
